package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author guozh
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    @Override
    public Result queryBlogById(Long id) {
        // 1.查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("博客不存在");
        }
        // 2.查询blog有关的用户
        User byId = userService.getById(blog.getUserId());
        blog.setIcon(byId.getIcon());
        blog.setName(byId.getNickName());
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    /**
     * 判断当前用户是否已经点赞
     *
     * @param blog 博客
     */
    private void isBlogLiked(Blog blog) {
        //  1.查询登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 3.如果未登录，无需查询
            return;
        }
        // 2.判断当前用户是否已经点赞 redis set 集合
        Double score = stringRedisTemplate.opsForZSet().score("blog:liked:" + blog.getId(), user.getId().toString());
        blog.setIsLike(score != null);
    }

    @Override
    public Result likeBlog(Long id) {
        //  1.查询登录用户
        UserDTO user = UserHolder.getUser();
        // 2.判断当前用户是否已经点赞 redis zset 集合
        Double score = stringRedisTemplate.opsForZSet().score("blog:liked:" + id, user.getId().toString());
        //  3.如果未点赞，可以点赞
        if (score == null) {
            //4.如果未点赞，可以点赞
            boolean isSuccess = update().setSql("liked = liked+ 1").eq("id", id).update();
            if (isSuccess) {
                //  4.1 修改redis
                stringRedisTemplate.opsForZSet().add("blog:liked:" + id, user.getId().toString(), System.currentTimeMillis());
                return Result.ok("点赞成功");
            }
        } else {
            //  5.如果已经点赞，则不能重复点赞 移除集合中的数据
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove("blog:liked:" + id, user.getId().toString());
                return Result.ok("取消点赞成功");
            }
        }
        return Result.fail("点赞失败");
    }

    @Override
    public Result queryBlogLikes(Long id) {
        //  查询top5
        String key = BLOG_LIKED_KEY + id;
        Set<String> range = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (range == null || range.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //  解析取出id
        List<Long> ids = range.stream().map(Long::parseLong).collect(Collectors.toList());

        String idStr = StrUtil.join(",", ids);
        // 查询用户 userService.listByIds(ids) 用的in不会按照id的顺序返回 应该改成 order by field
        List<UserDTO> userDtoS = userService.query().in("id", ids).last(" order by field(id," + idStr + ")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());

        return Result.ok(userDtoS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());

        // 2.保存探店博文
        boolean save = save(blog);
        if (!save) {
            return Result.fail("发布失败");
        }
        //  3.查询关注当前用户的用户
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();

        //  4.推送
        for (Follow follow : follows) {
            Long userId = follow.getUserId();
            stringRedisTemplate.opsForZSet().add(FEED_KEY + userId, blog.getId().toString(), System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();

        // 2.查询收件箱
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate
                .opsForZSet().reverseRangeByScoreWithScores(key,0,max,offset,3);

        // 3.解析数据
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        //遇见相同的最小时间跳过 1 2 3 3 4 5 第一次 查 123  不跳过 第二次查 334 需跳过一个 查 345
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String blogId = typedTuple.getValue();
            ids.add(Long.parseLong(blogId));
            long time = typedTuple.getScore().longValue();
            if (time == minTime) {
                os++;
            } else {
                minTime = time;
                os = 1;
            }
        }

        // 5.根据id查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("order by field(id," + idStr + ")").list();
        for (Blog blog : blogs) {
            User byId = userService.getById(blog.getUserId());
            blog.setIcon(byId.getIcon());
            blog.setName(byId.getNickName());
            isBlogLiked(blog);
        }
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
        });
        return Result.ok(records);
    }
}
